package com.lsz.atm.ui.commodity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.common.event.CommodityEvent;
import com.common.mvp.BaseMvpActivity;
import com.common.widght.ScrollInterceptScrollView;
import com.lsz.atm.R;
import com.lsz.atm.TemporaryDataUtil;
import com.lsz.atm.db.CommodityBeanDao;
import com.lsz.atm.db.bean.CommodityBean;
import com.lsz.atm.db.bean.PackageBean;
import com.lsz.atm.db.dao_utils.DaoUtils;
import com.lsz.atm.json.commodity.BundlesBean;
import com.lsz.atm.json.commodity.CommoditiesBean;
import com.lsz.atm.json.commodity.ProposalsBean;
import com.lsz.atm.ui.commodity.module_view.PackageView;
import com.lsz.atm.ui.commodity.module_view.SpecificationView;
import com.lsz.atm.viewutil.BigDecimalUtils;
import com.lsz.atm.viewutil.SpannableUtil;
import com.util_code.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.BindView;

public class CommodityDetailActivity extends BaseMvpActivity<CommodityView, CommodityPresent> implements CommodityView, View.OnClickListener {

    @BindView(R.id.iv_commodity_banner)
    ImageView ivCommodityBanner;
    @BindView(R.id.tv_commodity_name)
    TextView tvCommodityName;
    @BindView(R.id.tv_commodity_amount)
    TextView tvCommodityAmount;
    @BindView(R.id.tv_commodity_english_name)
    TextView tvCommodityEnglishName;
    @BindView(R.id.tv_commodity_description)
    TextView tvCommodityDescription;
    @BindView(R.id.ll_specifications_view)
    LinearLayout llSpecificationsView;
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.tv_current_food)
    TextView tvCurrentFood;
    @BindView(R.id.sv_layout_commodity)
    ScrollInterceptScrollView svLayoutCommodity;

    @BindView(R.id.iv_order_delete)
    ImageView ivOrderDelete;
    @BindView(R.id.tv_order_number)
    TextView tvOrderNumber;
    @BindView(R.id.iv_order_add)
    ImageView ivOrderAdd;
    @BindView(R.id.tv_order_confirm)
    TextView tvOrderConfirm;

    private ProposalsBean proposalsBean;
    private PackageView packageView;
    private SpecificationView specificationView;
    private List<BundlesBean> bundlesList;
    private boolean isPackage = false;
    private boolean isChoices = false;

    public static void startActivity(Activity activity, ProposalsBean proposals) {
        Intent intent = new Intent(activity, CommodityDetailActivity.class);
        Bundle bundle = new Bundle();
        proposals.totalPriceList = proposals.priceSell;
        proposals.cSelectNumber = 0;
        bundle.putParcelable("ProposalsBean", proposals);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_commodity_detail;
    }

    @Override
    protected void setTranslateStatusBar(boolean barColor) {
        super.setTranslateStatusBar(false);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void setupView() {
        tvBack.setOnClickListener(this);
        tvOrderConfirm.setOnClickListener(this);
        ivOrderDelete.setOnClickListener(this);
        ivOrderAdd.setOnClickListener(this);
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        proposalsBean = intent.getParcelableExtra("ProposalsBean");
        setTextData();
    }

    private void setTextData() {
        tvCommodityName.setText(proposalsBean.name);
        String currency = getResources().getString(R.string.currency);
        String amount = currency + " " + BigDecimalUtils.round(proposalsBean.priceSell, 2);
        SpannableString textSpannable = SpannableUtil.setTextSpannable(amount, 1, amount.length());
        tvCommodityAmount.setText(textSpannable);
        tvCommodityEnglishName.setText(proposalsBean.alias);
        tvCommodityDescription.setText(proposalsBean.desc);
        String round = BigDecimalUtils.round(proposalsBean.totalPriceList, 2);
        tvCurrentFood.setText(getCurrentFood(round));

        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(getResources().getDrawable(R.drawable.bg_food_detail_banner));
        requestOptions.centerCrop();
        Glide.with(this).load(proposalsBean.imgFace).apply(requestOptions).into(ivCommodityBanner);

        tvOrderNumber.setVisibility(View.GONE);
        ivOrderDelete.setVisibility(View.GONE);
        tvOrderConfirm.setVisibility(View.GONE);

        commodityTypeView();
        svLayoutCommodity.smoothScrollTo(0, 20);
    }

    private void commodityTypeView() {
        if (proposalsBean.choices != null && proposalsBean.choices.size() > 0) {
            isChoices = true;
            specificationView = new SpecificationView(this);
            llSpecificationsView.addView(specificationView.getView());
            specificationView.setData(proposalsBean.choices);
        } else if (proposalsBean.bundles != null && proposalsBean.bundles.size() > 0) {
            isPackage = true;
            packageView = new PackageView(this);
            llSpecificationsView.addView(packageView.getView());
            packageView.setRvPackageList(proposalsBean.bundles);
            packageView.setOnPackageItemListener(packageListener);
            bundlesList = proposalsBean.bundles;
        } else {
//            CommodityBean commodityBean = DaoUtils.getCommodityInstance().loadById(proposalsBean.id);
//            if (commodityBean != null) {
            ivOrderAdd.setVisibility(View.VISIBLE);
//                tvOrderNumber.setVisibility(View.VISIBLE);
//                ivOrderDelete.setVisibility(View.VISIBLE);
//                tvOrderConfirm.setVisibility(View.VISIBLE);
//                tvCurrentFood.setText(getCurrentFood(commodityBean.totalPriceList));
//                tvOrderNumber.setText(commodityBean.cSelectNumber + "");
//            }
        }
    }

    private PackageListener packageListener = new PackageListener() {

        @Override
        public void onCommoditiesAdd(CommoditiesBean commoditiesBean) {
            bundlesList = proposalsBean.bundles;
            String totalPrice = getPresenter().totalPrice(proposalsBean, bundlesList);
            setAmoutData(totalPrice);
        }

        @Override
        public void onCommoditiesDelete(CommoditiesBean commoditiesBean) {
            bundlesList = proposalsBean.bundles;
            String totalPrice = getPresenter().totalPrice(proposalsBean, bundlesList);
            setAmoutData(totalPrice);
        }

    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                EventBus.getDefault().post(new CommodityEvent());
                finish();
                break;
            case R.id.tv_order_confirm:
                if (isPackage) {
                    setPackage();
                } else if (isChoices) {
                    //有规格
                } else {
                    setConventional();
                    EventBus.getDefault().post(new CommodityEvent());
                    finish();
                }
                break;
            case R.id.iv_order_delete:
                if (isPackage) {
                    setAddAndDelete(false);
                } else if (isChoices) {
                    //有规格
                } else {
                    setAddAndDelete(false);
                }
                break;
            case R.id.iv_order_add:
                if (isPackage) {
                    setAddAndDelete(true);
                } else if (isChoices) {
                    //有规格
                } else {
                    setAddAndDelete(true);
                }
                break;
            default:
                break;
        }
    }

    private void setPackage() {
        if (checkSelectListData(isPackage)) {
            CommodityBean commodityBean = DaoUtils.getCommodityInstance().loadById(proposalsBean.id);
            if (commodityBean != null) {
                boolean isequal = false;
                for (BundlesBean bundles : bundlesList) {
                    for (CommoditiesBean commoditie : bundles.commodities) {
                        List<PackageBean> packageList = DaoUtils.getPackageInstance().loadPackageByRandomId(commodityBean.randomId, commoditie.proComId);
                        if (packageList.size() > 0 && Integer.parseInt(packageList.get(0).buyMin) == Integer.parseInt(commoditie.buyMin)) {
                            isequal = true;
                        } else {
                            isequal = false;
                            break;
                        }
                    }
                }
                if (isequal) {
                    CommodityBean commodity = TemporaryDataUtil.getCommodityBean(proposalsBean);
                    commodityBean.isPackage = isPackage;
                    commodityBean.cSelectNumber = commodityBean.cSelectNumber + commodity.cSelectNumber;
                    commodityBean.totalPriceList = TemporaryDataUtil.getTotalAmount(commodityBean.priceSell, commodityBean.priceSell, commodityBean.cSelectNumber);
                    DaoUtils.getCommodityInstance().updateCommodity(commodityBean);
                } else {
                    insertPackageSQL();
                }
            } else {
                insertPackageSQL();
            }
            EventBus.getDefault().post(new CommodityEvent());
            finish();
        }
    }

    private void insertPackageSQL() {
        CommodityBean commodity = TemporaryDataUtil.getCommodityBean(proposalsBean);
        commodity.isPackage = isPackage;
        long randomId = DaoUtils.getCommodityInstance().insertCommodityObject(commodity);
        for (BundlesBean bundles : bundlesList) {
            for (CommoditiesBean commoditie : bundles.commodities) {
                PackageBean packageBean = TemporaryDataUtil.getPackageBean(commoditie, randomId);
                DaoUtils.getPackageInstance().insertPackageObject(packageBean);
            }
        }
    }

    private void setConventional() {
        CommodityBean commodityBean = DaoUtils.getCommodityInstance().loadById(proposalsBean.id);
        if (commodityBean != null) {
            commodityBean.isPackage = isPackage;
            commodityBean.cSelectNumber = commodityBean.cSelectNumber + proposalsBean.cSelectNumber;
            commodityBean.totalPriceList = TemporaryDataUtil.getTotalAmount(commodityBean.priceSell, commodityBean.priceSell, commodityBean.cSelectNumber);
            DaoUtils.getCommodityInstance().updateCommodity(commodityBean);
        } else {
            commodityBean = TemporaryDataUtil.getCommodityBean(proposalsBean);
            commodityBean.isPackage = isPackage;
            long randomId = DaoUtils.getCommodityInstance().insertCommodityObject(commodityBean);
        }
    }

    private void setAddAndDelete(boolean isAdd) {
        if (isAdd) {
            proposalsBean.cSelectNumber = proposalsBean.cSelectNumber + 1;
            if (proposalsBean.cSelectNumber == 1) {
                proposalsBean.totalPriceList = BigDecimalUtils.round(proposalsBean.priceSell, 2);
            } else {
                proposalsBean.totalPriceList = BigDecimalUtils.add(proposalsBean.totalPriceList, proposalsBean.priceSell, 2);
            }
        } else {
            proposalsBean.cSelectNumber = proposalsBean.cSelectNumber - 1;
            if (proposalsBean.cSelectNumber > 0) {
                proposalsBean.totalPriceList = BigDecimalUtils.sub(proposalsBean.totalPriceList, proposalsBean.priceSell, 2);
            } else {
                proposalsBean.totalPriceList = BigDecimalUtils.round(proposalsBean.priceSell, 2);
            }
        }
        String totalPrice = getPresenter().totalPrice(proposalsBean, bundlesList);
        setAmoutData(totalPrice);
    }

    private void setAmoutData(String totalPrice) {
        if (proposalsBean.cSelectNumber == 0) {
            tvOrderNumber.setVisibility(View.GONE);
            ivOrderDelete.setVisibility(View.GONE);
            tvOrderConfirm.setVisibility(View.GONE);
        } else {
            tvOrderNumber.setVisibility(View.VISIBLE);
            ivOrderDelete.setVisibility(View.VISIBLE);
            tvOrderConfirm.setVisibility(View.VISIBLE);
            tvOrderNumber.setText(proposalsBean.cSelectNumber + "");
        }
        tvCurrentFood.setText(getCurrentFood(totalPrice));
    }

    private SpannableString getCurrentFood(String totalAmount) {
        String currentFood = getResources().getString(R.string.order_current_food);
        String format = currentFood.replace("%1$d", totalAmount);
        SpannableString textSpannable = SpannableUtil.setTextSpannable(format, 6, format.length());
        return textSpannable;
    }

    private boolean checkSelectListData(boolean isBundles) {
        boolean isSelect = false;
        if (isBundles) {
            for (BundlesBean bundles : bundlesList) {
                if (!TextUtils.isEmpty(bundles.id) && !TextUtils.equals(bundles.id, "0")) {
                    int buyMin = 0;
                    for (CommoditiesBean commoditie : bundles.commodities) {
                        if (!TextUtils.isEmpty(commoditie.buyMin)) {
                            buyMin = buyMin + Integer.parseInt(commoditie.buyMin);
                        }
                    }
                    if (!TextUtils.isEmpty(bundles.buyNum) && Integer.parseInt(bundles.buyNum) == buyMin) {
                        isSelect = true;
                    } else {
                        isSelect = false;
                        break;
                    }
                } else if (TextUtils.equals(bundles.id, "0") && TextUtils.equals("必选餐品", bundles.name)) {
                    isSelect = true;
                }
            }
            if (!isSelect) {
                ToastUtils.showLongToast("请选满餐品");
            }
        } else if (isChoices) {
            //有规格
            isSelect = false;
        }
        return isSelect;
    }
}
